(function(factory) {
	if (typeof define === "function" && define.amd) {
		// AMD. Register as an anonymous module.
		define(['HteOS/TileManager',"HteOS/metro/View","HteOS/metro/ContextMenu" ],factory);
	} else {
		// Browser globals
		factory();
	}
}(function() {
	/**
	 * @author 李球 <service@hteos.com>
	 * @class HteOS.Metro 桌面组件
	 * @singleton
	 */
	HteOS.Metro = {

		/**
		 * @private
		 * 初始化桌面组件，由程序内部调用，请勿手工调用
		 */
		init: function() {
			
			var metro = $("<div class=\"hte-metro\">");
			$("<div class=\"navbar navbar-default hteos-header\">"+
				"<div class=\"navbar-brand hteos-brand\" >"+
					"<img  src=\""+HteOS.basePath+"images/logo.png\"> "+
						"<a href=\"#\"> <span class=\"segoe\">HteOS</span>"+
						"- <small>与众不同的 <span class=\"segoe\">Web</span>"+
					"</small>"+
					"</a>"+
				"</div>"+
				"</div>").appendTo(metro);
			//初始化DOM元素
			$('<div class="hte-metro-viewport hte-webkit-scrollbar">' + 
				'<div class="hte-metro-container">' +
						'<div class="hte-metro-inner"></div>' + 
					'</div>' + 
				'</div>').appendTo(metro);
				
			//$("<div class=\"hte-metro-group-nav\"></div>").appendTo(".hte-metro");
			metro.appendTo($(document.body));
			var metro = this;
			var el = metro.getEl();
			
			// 如果发生浏览器改变大小，则自动调整位置
			$(window).resize(function() {
				metro.layout();
			});
			
			HteOS.EventManager.on("hte.apps.instantiated",function(){
				metro.render();
			});
			
			//$('.hte-metro-container').perfectScrollbar();
			//$('.hte-metro-container').css("overflow","hidden");
			
			if(HteOS.UA.Mobile){
				$('.hte-metro').width($(document.dody).width());
			}
			HteOS.metro.ContextMenu.init();
			
			//点击磁贴时执行应用
			$(document.body).on("click", ".hte-tile", function(event) {
				var app = HteOS.app.AppManager.getByEl($(this));
				HteOS.TaskManager.start(app);
				event.stopPropagation();
			});
			
			//初始化创建应用的钩子
			//HteOS.metro.Hook.init();
		},

		getEl: function() {
			return $(".hte-metro");
		},
		
		render : function(){
			// 计算尺寸
			this.layout();
			HteOS.metro.View.init();
			$(".hte-preloader").fadeOut();
			this.animate();
			HteOS.EventManager.trigger("hte.metro.render");
			this.rendered = true;
		},
		
		animate : function(){
			function translate(el){
  				if(!el.hasClass("hte-metro-group")) return;
  				el.css({
			       transform: "translateX(0px) scale(1)",
 		           opacity: 1
  				});
  				window.setTimeout(function(){
  					translate(el.next(".hte-metro-group"));
  				},20);
  			}
  			translate($(".hte-metro-group").eq(0));
		},

		/**
		 * 计算桌面的尺寸
		 */
		layout: function() {
			var me = this;
			var containerHeight = $(document).height() - 
				$(".hteos-header").outerHeight() - 
				$(".hte-dockbar").outerHeight() -
				$(".hte-taskbar").outerHeight();
			me.getEl().find(".hte-metro-container").height(containerHeight);
		}
	}
}));